<template>
  <!-- 顶部搜索区域，按钮区域 -->
  <div>
    <el-card class="box-card">
      <el-row>
        <el-col :span="6">
          订单编号：<el-input
            v-model="serachModel.orderNumber"
            placeholder="订单编号"
            clearable
            style="width: 280px; margin-right: 10px"
          ></el-input>
        </el-col>
        <el-col :span="6">
          收货手机号：<el-input
            v-model="serachModel.phone"
            placeholder="收货手机号"
            clearable
            style="width: 180px; margin-right: 10px"
          ></el-input>
        </el-col>

        <el-col :span="6">
          发货日期：
          <el-date-picker
            v-model="serachModel.deliveryDate"
            type="date"
            placeholder="选择日期"
            style="width: 180px; margin-right: 10px"
            width="180px"
            value-format="yyyy-MM-dd HH:mm:ss"
            clearable
          >
          </el-date-picker>
        </el-col>
        <el-col :span="6">
          排序方式：
          <el-select
            v-model="serachModel.orderByDesc"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <!-- 按钮区域 -->
        <el-col :span="16" style="margin-top: 10px">
          <el-button type="primary" @click="getOrderList">查询</el-button>

          <el-button type="danger" @click="deleteOrderByIds"
            >批量删除</el-button
          >
        </el-col>
        <el-col :span="8" align="right" style="margin-top: 10px">
          <el-button
            v-if="orderStatus === '订单处理'"
            type="primary"
            style="margin-right: 10px"
            @click="OpenGoodsUi"
            >批量更新库存状态</el-button
          >

          <span v-if="orderRemarkStatus != 0">
            <el-badge :value="orderRemarkStatus" class="item">
              <el-button @click="OrderRemarkVisible = true" type="warning"
                >登记</el-button
              >
            </el-badge>
          </span>
          <span v-else>
            <el-button @click="OrderRemarkVisible = true">登记</el-button>
          </span>
        </el-col>
      </el-row>
    </el-card>

    <el-card>
      <el-tabs v-model="orderStatus" @tab-click="handleClick">
        <el-tab-pane label="订单处理" name="订单处理"></el-tab-pane>
        <el-tab-pane label="代发" name="代发"></el-tab-pane>
        <el-tab-pane label="采购" name="采购"></el-tab-pane>
      </el-tabs>
      <el-table
        :data="orderList"
        style="width: 100%"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="50"> </el-table-column>

        <el-table-column prop="creditRating" label="订单信息" width="480" fixed>
          <template slot-scope="scope">
            标记记录：<span style="color: #f56c6c"
              >{{ scope.row.creditRating }}
            </span>
            <br />
            <span>平台：{{ scope.row.orderPlatform }} </span>
            <br />
            <!-- 判断是否有重复订单编号 -->
            <el-badge is-dot v-if="isExist(scope.row.orderLogs, 'orderNumber')">
              <span
                >订单编号：<el-button
                  type="text"
                  class="btn-copy"
                  :data-clipboard-text="scope.row.orderNumber"
                  @click="copyMessage()"
                  >{{ scope.row.orderNumber }}</el-button
                >
              </span>
            </el-badge>
            <span v-else
              >订单编号：<el-button
                type="text"
                class="btn-copy"
                :data-clipboard-text="scope.row.orderNumber"
                @click="copyMessage()"
                >{{ scope.row.orderNumber }}</el-button
              >
            </span>
            <br />
            型号：<strong>{{ scope.row.tradeName }}</strong>
            <br />
            套餐：<strong>{{ scope.row.setMeal }}</strong>
            <br />
            配件：<strong>{{ scope.row.attachment }}</strong>
            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'orderInfo')"
              >编辑</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="发货信息" width="240">
          <template slot-scope="scope">
            发货日：
            <span
              v-if="
                scope.row.deliveryDate != null &&
                scope.row.deliveryDate != undefined
              "
            >
              <span v-if="isDateBeforeToday(scope.row.deliveryDate)">{{
                scope.row.deliveryDate
                  .split(" ")[0]
                  .substring(0, scope.row.deliveryDate.split("T")[0].length)
              }}</span>
              <span style="color: #f56c6c" v-else>
                {{
                  scope.row.deliveryDate
                    .split(" ")[0]
                    .substring(0, scope.row.deliveryDate.split("T")[0].length)
                }}
              </span>
              <br />
              运费：
              <span>
                {{ scope.row.freight }}
              </span>
              <br />
              寄出单号：
              <span>
                {{ scope.row.trackingNumber }}
              </span>
              <br />
              寄回单号：
              <span>
                {{ scope.row.receiptNumber }}
              </span>
              <br />
              签收单号：
              <span>
                {{ scope.row.getReceiptNumber }}
              </span>
              <br />
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="OpenEditUi(scope.row.id, 'sendInfo')"
                >编辑</el-button
              >
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="remark" label="备注" width="260">
          <template slot-scope="scope">
            <div
              v-show="!scope.row.remarkEdit"
              @click="scope.row.remarkEdit = !scope.row.remarkEdit"
            >
              {{
                scope.row.remark == null || scope.row.remark.trim() == ""
                  ? "......"
                  : scope.row.remark
              }}
            </div>

            <div v-show="scope.row.remarkEdit">
              <el-input v-model="scope.row.remark"></el-input>
              <el-button type="text" @click="updateOrderRemark(scope.row)"
                >保存</el-button
              >
              <el-button type="text" @click="getOrderList()">取消</el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="" label="租期" width="180">
          <template slot-scope="scope">
            <strong style="font-size: 14px">
              {{
                startAndEndTime(scope.row.startTime, scope.row.endTime)
              }}</strong
            >
            <br />
            <strong v-if="scope.row.duration >= 90" style="color: #f56c6c">
              {{ durationAndMoney(scope.row.duration, scope.row.money) }}
            </strong>
            <strong v-else>
              {{ durationAndMoney(scope.row.duration, scope.row.money) }}
            </strong>
            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'rentTimeInfo')"
              >编辑</el-button
            >
          </template>
        </el-table-column>

        <el-table-column label="客户收货信息" width="360">
          <template slot-scope="scope">
            <span>收 件 人：</span><strong>{{ scope.row.userName }}</strong>
            <span style="padding: 6px"></span>
            <br />
            <span>手 机 号：</span
            ><el-badge
              is-dot
              class="item"
              v-if="isExist(scope.row.orderLogs, 'userinfo')"
              ><el-button
                type="text"
                class="btn-copy"
                :data-clipboard-text="scope.row.phone"
                @click="copyMessage()"
                ><strong>{{ scope.row.phone }}</strong></el-button
              ></el-badge
            >
            <el-button
              v-else
              type="text"
              class="btn-copy"
              :data-clipboard-text="scope.row.phone"
              @click="copyMessage()"
              ><strong>{{ scope.row.phone }}</strong></el-button
            >
            <br />
            <el-row
              ><el-col :span="5">收件地址：</el-col
              ><el-col :span="19">
                <strong>{{ scope.row.address }}</strong></el-col
              ></el-row
            >

            <br />
            <el-button
              type="text"
              size="mini"
              icon="el-icon-edit"
              @click="OpenEditUi(scope.row.id, 'userInfo')"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="btn-copy"
              :data-clipboard-text="getAddressInfo(scope.row)"
              @click="copyMessage()"
              >复制收货信息</el-button
            >
          </template>
        </el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态" width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.debitStatus != '已扣款'" type="warning">{{
              scope.row.debitStatus
            }}</el-tag>

            <br />
            <span v-if="scope.row.stockStatus != '已减库存'">
              <el-tag v-if="scope.row.stockStatus == '没有库存'" type="danger">
                {{ scope.row.stockStatus }}
              </el-tag>
              <el-tag v-else>{{ scope.row.stockStatus }}</el-tag>
            </span>

            <br />
            <el-tag v-if="scope.row.addressStatus != '正常'" type="warning">{{
              scope.row.addressStatus
            }}</el-tag>

            <br />
          </template>
        </el-table-column>
        <!-- 日志 -->
        <el-table-column label="订单日志">
          <template slot-scope="scope">
            <!-- 显示两天最新的日志 -->
            <div v-if="scope.row.orderLogs.length > 0">
              <el-popover
                placement="left"
                title="订单日志"
                width="520"
                trigger="hover"
              >
                <el-timeline>
                  <el-timeline-item
                    v-for="(logs, index) in scope.row.orderLogs"
                    :key="index"
                    :timestamp="logs.createTime"
                    :color="logs.type == false ? '#909399' : '#409EFF'"
                  >
                    <span>{{ logs.operator }}</span>
                    <span
                      v-if="
                        logs.log === '补发订单' ||
                        logs.log === '重复订单' ||
                        logs.log === '转寄订单'
                      "
                      style="color: #f56c6c"
                    >
                      {{ logs.log }}</span
                    >
                    <span v-else> {{ logs.log }}</span>
                  </el-timeline-item>
                </el-timeline>

                <el-badge
                  v-if="getSpecialOrderNum(scope.row.orderLogs) > 0"
                  :value="getSpecialOrderNum(scope.row.orderLogs)"
                  class="item"
                  slot="reference"
                  style="margin-top: 10px"
                >
                  <el-button type="text">
                    <strong>{{ scope.row.orderLogs[0].log }}</strong>
                  </el-button>
                </el-badge>
                <el-button type="text" slot="reference" v-else>
                  <strong>{{ scope.row.orderLogs[0].log }}</strong>
                </el-button>
              </el-popover>
              <!-- 添加日志时间 -->
              <div>
                <span style="margin-right: 6px">{{
                  scope.row.orderLogs[0].operator
                }}</span
                ><span>{{ scope.row.orderLogs[0].createTime }}</span>
              </div>
            </div>

            <el-button type="text" @click="openAddlogUi(scope.row)"
              >添加日志</el-button
            >
          </template>
        </el-table-column>
        <!-- 状态 -->

        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-col :span="12">
                <el-dropdown trigger="click" @command="handleCommand">
                  <el-button type="primary" size="mini">
                    订单状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '已标记',
                      }"
                      >已标记</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '订单处理',
                      }"
                      >订单处理</el-dropdown-item
                    >

                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '代发',
                      }"
                      >代 发</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '采购',
                      }"
                      >采购</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'orderStatus',
                        status: '待取消',
                      }"
                      >待取消</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    库存状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '未减库存',
                      }"
                      >未减库存</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '已减库存',
                      }"
                      >已减库存</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'stockStatus',
                        status: '没有库存',
                      }"
                      >没有库存</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    地址状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '正常',
                      }"
                      >正常</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '地址需核实',
                      }"
                      >地址需核实</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'addressStatus',
                        status: '收货秘钥',
                      }"
                      >收货秘钥</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>

                <el-dropdown
                  trigger="click"
                  style="margin-top: 6px"
                  @command="handleCommand"
                >
                  <el-button type="primary" size="mini">
                    扣款状态<i class="el-icon-arrow-down el-icon--right"></i>
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'debitStatus',
                        status: '未扣款',
                      }"
                      >未扣款</el-dropdown-item
                    >
                    <el-dropdown-item
                      :command="{
                        id: scope.row.id,
                        model: 'debitStatus',
                        status: '已扣款',
                      }"
                      >已扣款</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
              <el-col :span="12">
                <el-button
                  v-if="scope.row.orderStatus != '订单处理'"
                  size="mini"
                  style="margin-top: 10px"
                  @click="OpenSendOrderUi(scope.row.id)"
                  >发 货</el-button
                >
                <el-button
                  v-else
                  size="mini"
                  style="margin-top: 10px"
                  @click="
                    updateOrderStatus({
                      id: scope.row.id,
                      model: 'orderStatus',
                      status: '待发货',
                    })
                  "
                  >待发货</el-button
                >
                <br />
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteOrderById(scope.row)"
                  style="margin-top: 10px"
                  >删 除</el-button
                >
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="serachModel.pageNo"
      :page-sizes="[20, 40, 60, 80]"
      :page-size="serachModel.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 编辑订单对话 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      @close="cleaForm"
      :before-close="handleClose"
      width="820px"
    >
      <el-form
        :model="orderForm"
        class="demo-form-inline"
        ref="orderFormRef"
        :rules="rules"
      >
        <el-row v-if="EditUiType.orderInfo">
          <el-form-item label="标记记录" :label-width="formLabelWidth">
            <el-input
              v-model="orderForm.creditRating"
              placeholder="标记记录"
            ></el-input>
          </el-form-item>
          <el-form-item label="平台" :label-width="formLabelWidth">
            <el-input
              v-model="orderForm.orderPlatform"
              placeholder="平台"
            ></el-input>
          </el-form-item>
          <el-form-item
            id=""
            label="订单编号"
            prop="orderNumber"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.orderNumber"
              autocomplete="off"
              placeholder="订单编号"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="型 号"
            prop="tradeName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.tradeName"
              autocomplete="off"
              placeholder="型 号"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="商品名称"
            prop="setMeal"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.setMeal"
              autocomplete="off"
              placeholder="商品名称"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="配件"
            prop="attachment"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.attachment"
              autocomplete="off"
              placeholder="配件"
            ></el-input
          ></el-form-item>
        </el-row>

        <el-row v-if="EditUiType.sendInfo">
          <el-form-item
            label="时 效"
            prop="ageing"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.number="orderForm.ageing"
              label="时 效"
              placeholder="时 效"
            ></el-input
          ></el-form-item>

          <el-form-item
            label="运 费"
            prop="freight"
            :label-width="formLabelWidth"
          >
            <el-select v-model="orderForm.freight" placeholder="运费">
              <el-option label="寄 付" value="寄付"></el-option>
              <el-option label="包 邮" value="包邮"></el-option>
              <el-option label="到 付" value=""></el-option>
              <el-option label="特快寄付" value="特快寄付"></el-option>
              <el-option label="特快到付" value="特快到付"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row v-if="EditUiType.remarkInfo">
          <el-form-item
            label="备 注"
            prop="remark"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="orderForm.remark"
            >
            </el-input>
          </el-form-item>
        </el-row>

        <el-row v-if="EditUiType.rentTimeInfo">
          <el-form-item label="起租日" :label-width="formLabelWidth">
            <el-date-picker
              v-model="orderForm.startTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束日" :label-width="formLabelWidth">
            <el-date-picker
              v-model="orderForm.endTime"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item
            label="天数"
            prop="duration"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.number="orderForm.duration"
              autocomplete="off"
              placeholder="天数"
            ></el-input>
          </el-form-item>

          <el-form-item label="租金" prop="money" :label-width="formLabelWidth">
            <el-input
              v-model.number="orderForm.money"
              autocomplete="off"
              placeholder="租金"
            ></el-input>
          </el-form-item>
        </el-row>

        <el-row v-if="EditUiType.userInfo">
          <el-form-item
            label="收 件 人"
            prop="userName"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.userName"
              autocomplete="off"
              placeholder="收件人"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="收货手机号"
            prop="phone"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.phone"
              autocomplete="off"
              placeholder="收货手机号"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="收货地址"
            prop="address"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="orderForm.address"
              autocomplete="off"
              placeholder="收货地址"
            ></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrder()">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
      title="登记订单备注"
      :visible.sync="OrderRemarkVisible"
      direction="rtl"
      size="50%"
    >
      <el-card>
        <el-row
          ><el-col :span="24" align="right" style="margin: 10px">
            <el-button type="primary" @click="OrderRemarkUi(null)"
              >新增</el-button
            ></el-col
          ></el-row
        >
        <el-row>
          <el-col :span="24">
            <el-table :data="orderRemarData">
              <el-table-column property="phone" label="手机号" width="150">
                <template slot-scope="scope">
                  <span v-if="scope.row.status">
                    <el-badge is-dot style="margin-top: 10px">{{
                      scope.row.phone
                    }}</el-badge>
                  </span>
                  <span v-else>
                    {{ scope.row.phone }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column property="remark" label="备注">
              </el-table-column>

              <el-table-column
                property="createTime"
                label="创建时间"
                width="180px"
              >
              </el-table-column>

              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button @click="OrderRemarkUi(scope.row)">编辑</el-button>
                  <el-button type="danger" @click="DeleteRemarkById(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-card>
    </el-drawer>

    <!-- 登记订单对话框 -->
    <el-dialog
      :title="orderRemarkTitle"
      :visible.sync="dialogVisibleOrderRemark"
      width="30%"
      @close="cleaForm"
      :before-close="handleClose"
    >
      <el-form
        :model="orderRemarkForm"
        class="demo-form-inline"
        ref="orderRemarkFormRef"
        :rules="OrderRemarkRules"
      >
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input
            v-model="orderRemarkForm.phone"
            placeholder="手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input
            v-model="orderRemarkForm.remark"
            placeholder="备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOrderRemark = false">取 消</el-button>
        <el-button type="primary" @click="saveOrderRemark">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="自定义日志"
      :visible.sync="dialogVisibleLog"
      width="520px"
      :before-close="handleClose"
      @close="clearLogForm"
    >
      <el-form label-width="80px" :model="userLogForm">
        <el-form-item label="订单类型">
          <el-checkbox-group v-model="userLogForm.types">
            <el-checkbox label="补发订单" name="type"></el-checkbox>
            <el-checkbox label="重复订单" name="type"></el-checkbox>
            <el-checkbox label="转寄订单" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="输入日志">
          <el-input
            type="textarea"
            :rows="4"
            v-model="userLogForm.log"
            width="400"
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleLog = false">取 消</el-button>
        <el-button type="primary" @click="addUserLog">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 发货对话框 -->
    <el-dialog
      title="发货"
      :visible.sync="dialogVisibleSendProduct"
      width="520px"
      :before-close="handleClose"
      @close="cleaSendOrderForm"
    >
      <el-form
        label-width="80px"
        :model="sendProductForm"
        ref="sendOrderRef"
        :rules="SendOrderRules"
      >
        <el-form-item label="序列号" prop="serialNumber">
          <el-input
            v-model="sendProductForm.serialNumber"
            width="400"
            placeholder="序列号"
          ></el-input>
        </el-form-item>
        <el-form-item label="运单号" prop="trackingNumber">
          <el-input
            v-model="sendProductForm.trackingNumber"
            width="400"
            placeholder="运单号"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleSendProduct = false">取 消</el-button>
        <el-button
          type="primary"
          @click="sendProduct"
          :loading="sendProductLoading"
          >发 货</el-button
        >
      </span>
    </el-dialog>

    <!-- 批量减库存对话框 -->
    <el-dialog
      title="更新库存"
      :visible.sync="dialogTableVisibleGoods"
      :before-close="handleClose"
      @close="clearGoods"
    >
      <el-row>
        <el-col :span="12">
          库存状态：
          <el-select
            v-model="seleceStatusCode"
            placeholder="请选择"
            @change="OpenGoodsUi"
          >
            <el-option
              v-for="item in stockStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.value == statusCode ? true : false"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="12">
          更新库存状态：
          <el-select v-model="statusCode" placeholder="请选择" clearable>
            <el-option
              v-for="item in stockStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.value == seleceStatusCode ? true : false"
            >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row>
        <el-tabs v-model="activeName" type="card" style="margin-top: 10px">
          <el-tab-pane label="设备列表" name="first">
            <el-table
              :data="GoodsList"
              ref="singleTable"
              @selection-change="handleSelectionChangeGoodsList"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column prop="orderPlatform" label=" 平 台" width="80">
              </el-table-column>
              <el-table-column prop="orderNumber" label="订单编号" width="200">
                <template slot-scope="scope">
                  <span>
                    <el-link
                      :underline="false"
                      class="btn-copy"
                      :data-clipboard-text="scope.row.orderNumber"
                      @click="copyMessage()"
                      >{{ scope.row.orderNumber }}</el-link
                    >
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="tradeName" label="型号" width="180">
              </el-table-column>

              <el-table-column prop="userName" label="姓名" width="90">
              </el-table-column>
              <el-table-column prop="phone" label="电话" width="180">
              </el-table-column>
              <el-table-column prop="address" label="地址"> </el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click.native.prevent="deleteRow(scope.$index, GoodsList)"
                    >删 除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="设备统计" name="second">
            <el-card class="box-card">
              <div
                v-for="(value, key) in getGoodsListSum"
                :key="key"
                style="margin-top: 10px"
              >
                {{ key }} : {{ value }}
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-row>

      <el-row>
        <el-col align="right" style="margin-top: 16px; margin-right: 20px">
          <el-button type="primary" size="smell" @click="updateStockStatus()"
            >确 定</el-button
          >
          <el-button @click="dialogTableVisibleGoods = false" size="smell"
            >取 消</el-button
          >
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import orderApi from "@/api/order";
import orderRemarkApi from "@/api/orderRemark";
import orderLogApi from "@/api/orderLog";
import ClipboardJS from "clipboard"; // 复制

export default {
  mounted() {
    new ClipboardJS(".btn-copy"); // 复制文本
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      var reg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (!reg.test(value)) {
        return callback(new Error("手机格式错误"));
      }
      callback();
    };

    var checkSerilNum = (rule, value, callback) => {
      var reg =
        /^(?=.*[0-9a-zA-Z-])(?=.{4,20}$)(?:(?=.*\d)|(?=.*-))[0-9a-zA-Z-]*$/;
      if (value.length > 26 || value.length < 4) {
        return callback(new Error("序列号长度不对(4-26个字符)"));
      }
      if (!reg.test(value)) {
        return callback(new Error("序列号不合法"));
      }
      callback();
    };
    return {
      // 库存状态
      stockStatus: [
        {
          value: "未减库存",
          label: "未减库存",
        },
        {
          value: "已减库存",
          label: "已减库存",
        },
        {
          value: "没有库存",
          label: "没有库存",
        },
      ],
      seleceStatusCode: "未减库存",
      statusCode: "",

      activeName: "first",
      // 勾选的设备（{设备名称，客户信息}）
      GoodsList: [],

      //  设备求和({设备名称：数量})
      GoodsSum: {},

      dialogTableVisibleGoods: false,

      // 发货对话框
      dialogVisibleSendProduct: false,
      // 对话框显示类型
      EditUiType: {
        orderInfo: false,
        sendInfo: false,
        remarkInfo: false,
        rentTimeInfo: false,
        userInfo: false,
        statusInfo: false,
      },

      OrderRemarkVisible: false,
      // 订单状态
      orderStatus: "订单处理",

      formLabelWidth: "130px",

      loading: false,
      // 对话框标题
      title: "",
      // 对话框是否可见
      dialogFormVisible: false,

      total: 0,
      serachModel: {
        pageNo: 1,
        pageSize: 20,
      },
      orderForm: {},
      orderList: [],
      // 复选框
      multipleSelection: [],

      multipleSelectionGoodsList: [],
      // 排序方式
      options: [
        {
          value: "平台",
          label: "平台",
        },
        {
          value: "发货日",
          label: "发货日",
        },
        {
          value: "型号",
          label: "型号",
        },
        {
          value: "起租日",
          label: "起租日",
        },
      ],
      // 修改模式
      model: "",

      rules: {
        tradeName: [
          { required: true, message: "请输入型号", trigger: "blur" },
          {
            min: 2,
            max: 100,
            message: "长度在 2 到 100 个字符",
            trigger: "blur",
          },
        ],
        setMeal: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          {
            min: 2,
            max: 255,
            message: "长度在 2 到 255 个字符",
            trigger: "blur",
          },
        ],
        userName: [
          { required: true, message: "请输入收件人", trigger: "blur" },
          {
            min: 1,
            max: 26,
            message: "长度在 1 到 26 个字符",
            trigger: "blur",
          },
        ],
        address: [
          { required: true, message: "请输入收货地址", trigger: "blur" },
          {
            min: 12,
            max: 255,
            message: "长度在 12 到 255 个字符",
            trigger: "blur",
          },
        ],

        phone: [{ validator: checkPhone, trigger: "blur" }],
        money: [{ type: "number", message: "请输入正确的金额" }],
        duration: [
          {
            type: "number",
            message: "请输入正确的租期天数",
          },
        ],
      },
      OrderRemarkRules: {
        phone: [{ validator: checkPhone, trigger: "blur" }],
        remark: [
          { required: true, message: "请输入备注", trigger: "blur" },
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur",
          },
        ],
      },
      SendOrderRules: {
        serialNumber: [
          { required: true, message: "请输入序列号", trigger: "blur" },
          {
            min: 1,
            max: 32,
            message: "长度在 6 到 64 个字符",
            trigger: "blur",
          },
        ],
        trackingNumber: [
          { required: true, message: "请输入备注", trigger: "blur" },
          {
            min: 1,
            max: 255,
            message: "长度在 1 到 255 个字符",
            trigger: "blur",
          },
        ],
      },

      // 发货表单
      sendProductForm: {},

      // 订单登记的撞击的条数
      orderRemarkTitle: "",
      orderRemarkStatus: 0,
      OrderRemarkVisible: false,
      orderRemarData: [],
      orderRemarkForm: {},

      dialogVisibleOrderRemark: false,

      // 自定义日志对话框
      dialogVisibleLog: false,

      userLogForm: { types: [] },

      sendProductLoading: false,
    };
  },
  methods: {
    // 清空自定义日志对话框
    clearLogForm() {
      // 自定义日志
      // 清空表单数据
      this.userLogForm = {
        types: [],
      };
    },
    // 确认关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 清除表单数据
    clearGoods() {
      this.activeName = "first";
      // 勾选的设备（{设备名称，客户信息}）
      this.GoodsList = [];

      //  设备求和({设备名称：数量})
      this.GoodsSum = {};
    },

    handleSizeChange(pageSize) {
      this.serachModel.pageSize = pageSize;
      this.getOrderList();
    },
    handleCurrentChange(pageNo) {
      this.serachModel.pageNo = pageNo;
      this.getOrderList();
    },
    // 清理表单数据
    cleaForm() {
      // 清理数据
      this.orderForm = {};
      if (
        this.$refs.orderFormRef != null &&
        this.$refs.orderFormRef != undefined
      ) {
        this.$refs.orderFormRef.clearValidate();
      }
      this.orderRemarkForm = {};
      if (
        this.$refs.orderRemarkFormRef != null &&
        this.$refs.orderRemarkFormRef != undefined
      ) {
        this.$refs.orderRemarkFormRef.clearValidate();
      }
    },
    cleaSendOrderForm() {
      // 清理数据
      this.cleaSendOrderForm = {};
      if (
        this.$refs.sendOrderRef != null &&
        this.$refs.sendOrderRef != undefined
      ) {
        this.$refs.sendOrderRef.clearValidate();
      }
    },

    getOrderList() {
      this.loading = true;
      orderApi
        .getOrderList(this.serachModel, this.orderStatus)
        .then((response) => {
          // 给获取的List加一个字段
          this.addEdit(response.data.rows);
          this.total = response.data.total;
          this.loading = false;
        });
      orderRemarkApi.getOrderRemarkList().then((response) => {
        this.orderRemarkStatus = 0;
        this.orderRemarData = response.data;
        this.ji_suan_status(response.data);
      });
    },
    addEdit(orderList) {
      orderList.forEach((item) => {
        item.remarkEdit = false;
      });

      this.orderList = orderList;
    },
    // 计算订单备注小提示框的数字
    ji_suan_status(orderRemars) {
      if (orderRemars != null && orderRemars != undefined) {
        orderRemars.forEach((item) => {
          if (item.status) {
            this.orderRemarkStatus += 1;
          }
        });
      }
    },

    handleSelectionChange(val) {
      // 保存选中的对象
      this.multipleSelection = val;
    },

    handleSelectionChangeGoodsList(val) {
      this.multipleSelectionGoodsList = val;
    },

    // 租期框计算
    startAndEndTime(startTime, endTime) {
      if (
        (startTime != null || startTime != undefined) &&
        (endTime != null || endTime != undefined)
      )
        return startTime.substring(5, 10) + "-" + endTime.substring(5, 10);
      else return null;
    },

    durationAndMoney(duration, money) {
      if (
        (duration != null || duration != undefined) &&
        (money != null || money != undefined)
      )
        return duration + "天," + money + "元";
    },

    // 添加订单
    saveOrder() {
      this.$refs.orderFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 提交数据给后台
          orderApi.saveOrder(this.orderForm, this.model).then((response) => {
            if (response.code == 20000) {
              this.$message({
                showClose: true,
                message: response.message,
                type: "success",
              });
              // 关闭对话框
              this.dialogFormVisible = false;
              // 刷新表单
              this.getOrderList();
              this.loading = false;
            } else {
              this.$notify({
                title: "警告",
                message: response.message,
                type: "warning",
                duration: 0,
              });
              // 关闭对话框
              this.dialogFormVisible = false;
              // 刷新表单
              this.getOrderList();
              this.loading = false;
            }
          });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.loading = false;
          return false;
        }
      });
    },

    // 显示对话框
    OpenEditUi(orderId, type) {
      if (type != null && type != undefined) {
        // 订单信息
        if (type == "orderInfo") {
          this.EditUiType = {
            orderInfo: true,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "sendInfo") {
          // 发货信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: true,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "rentTimeInfo") {
          // 租期信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: true,
            userInfo: false,
            statusInfo: false,
          };
        } else if (type == "userInfo") {
          // 客户信息
          this.EditUiType = {
            orderInfo: false,
            sendInfo: false,
            remarkInfo: false,
            rentTimeInfo: false,
            userInfo: true,
            statusInfo: false,
          };
        }
      }

      if (orderId == null || orderId == undefined) {
        this.title = "添加订单";
        this.dialogFormVisible = true;
      } else {
        this.title = "修改订单";
        this.loading = true;
        orderApi.getOrderById(orderId).then((response) => {
          this.orderForm = response.data;
          this.loading = false;
        });

        this.model = type;
        this.loading = false;
        this.dialogFormVisible = true;
      }
    },

    // 更新订单备注
    updateOrderRemark(order) {
      var model = "remarkInfo";
      var pushOrder = {
        id: order.id,
        orderNumber: order.orderNumber,
        remark: order.remark,
        orderStatus: order.orderStatus,
        stockStatus: order.stockStatus,
        debitStatus: order.debitStatus,
        addressStatus: order.addressStatus,
        startTime: order.startTime,
        ageing: order.ageing,
      };
      // 提交数据给后台
      orderApi.saveOrder(pushOrder, model).then((response) => {
        this.$message({
          showClose: true,
          message: response.message,
          type: "success",
        });
        // 刷新表单
        this.getOrderList();
      });
    },

    // 删除订单
    deleteOrderById(order) {
      this.$confirm(`您确认该用户的删除订单 ${order.userName}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderApi.deleteOrderById(order.id).then((response) => {
            this.$message({
              type: "success",
              message: response.message,
            });
            this.getOrderList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 批量删除
    deleteOrderByIds() {
      if (
        this.multipleSelection != null ||
        this.multipleSelection != undefined
      ) {
        let ids = this.multipleSelection.map((order) => order.id);
        this.$confirm(`您确认要批量删除${ids.length}个订单 ?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            orderApi.deleteOrderByIds(ids).then((response) => {
              this.$message({
                type: "success",
                message: response.message,
              });
              this.getOrderList();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      }
    },

    // 发货日处理
    isDateBeforeToday(dateStr) {
      const inputDate = new Date(dateStr); // 创建输入日期的 JavaScript Date 对象
      const today = new Date(); // 获取今天的日期的 JavaScript Date 对象

      // 只比较日期部分，不比较时间，将时分秒都设置为 0
      inputDate.setHours(0, 0, 0, 0);
      today.setHours(0, 0, 0, 0);

      return inputDate >= today; // 比较日期
    },
    // tabs切喊
    handleClick(tab, event) {
      this.getOrderList();
    },

    // 修改订单状态
    updateOrderStatus(command) {
      this.$confirm(`您确认要修改状态为 ${command.status}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var UpdateModelAndStatus = {
            model: command.model,
            status: command.status,
          };
          orderApi
            .updateOrderStatus(command.id, UpdateModelAndStatus)
            .then((response) => {
              if (response.code === 20000) {
                this.$message({
                  type: "success",
                  message: response.message,
                });
              } else {
                this.$message({
                  type: "error",
                  message: response.message,
                });
              }
              this.getOrderList();
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消修改",
          });
        });
    },

    // 触发下单菜单
    handleCommand(command) {
      this.updateOrderStatus(command);
    },

    // 获取最新的前两条日志
    getNewLogs(logs) {
      var newLogs = [];
      if (logs.length > 2) {
        for (let i = 0; i < 2; i++) {
          newLogs.push(logs[i]);
        }
        return newLogs;
      } else {
        return logs;
      }
    },

    // 添加自定义日志
    openAddlogUi(row) {
      this.userLogForm.id = row.id;
      this.dialogVisibleLog = true;
    },
    addUserLog() {
      if (
        this.userLogForm.types.length == 0 &&
        (this.userLogForm.log == undefined || this.userLogForm.log == null)
      ) {
        this.$message({
          type: "error",
          message: "日志不能为空",
        });
      } else {
        orderLogApi.addLog(this.userLogForm).then((response) => {
          if (response.code == 20000) {
            this.$message({
              type: "success",
              message: response.message,
            });
            // 清空表单数据
            this.userLogForm = {
              types: [],
            };
            this.dialogVisibleLog = false;
            this.getOrderList();
          } else {
            this.$message({
              type: "error",
              message: response.message,
            });
          }
        });
      }
    },

    // 获取订单特殊订单个数
    getSpecialOrderNum(logs) {
      var num = 0;

      logs.forEach((item) => {
        if (
          item.log === "补发订单" ||
          item.log === "重复订单" ||
          item.log === "转寄订单"
        ) {
          num += 1;
        }
      });

      return num;
    },

    // 判断订单是否重复
    isExist(orderLogs, model) {
      if (orderLogs.length > 0) {
        if (model === "orderNumber") {
          for (const log of orderLogs) {
            if (log.log === "订单编号重复") {
              return true;
            }
          }
        } else if (model === "userinfo") {
          for (const log of orderLogs) {
            if (log.log === "客户信息重复") {
              return true;
            }
          }
        }
      } else {
        return false;
      }
    },

    // 点击复制提示
    copyMessage() {
      this.$message({
        type: "success",
        message: "复制成功",
      });
    },

    // 获取收货信息
    getAddressInfo(row) {
      var username = row.userName;
      var phone = row.phone;
      var address = row.address;

      return username + "," + phone + "," + address;
    },

    // 显示订单处理UI
    OrderRemarkUi(remark) {
      if (remark == null || remark == undefined) {
        this.orderRemarkTitle = "新增登记记录";
        this.dialogVisibleOrderRemark = true;
      } else {
        this.orderRemarkTitle = "修改登记记录";
        this.loading = true;
        orderRemarkApi.getOrderRemarkById(remark.id).then((response) => {
          this.orderRemarkForm = response.data;
          this.loading = false;
        });
        this.loading = false;
        this.dialogVisibleOrderRemark = true;
      }
    },

    DeleteRemarkById(remark) {
      this.$confirm(`您确认该用户的删除订单 ${remark.phone}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderRemarkApi.deleteOrderRemarkById(remark.id).then((response) => {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.getOrderList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    saveOrderRemark() {
      this.$refs.orderRemarkFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          // 提交数据给后台
          orderRemarkApi
            .saveOrderRemark(this.orderRemarkForm)
            .then((response) => {
              if (response.code === 20000) {
                this.$message({
                  showClose: true,
                  message: response.message,
                  type: "success",
                });
                // 关闭对话框
                this.dialogVisibleOrderRemark = false;
                // 刷新表单
                this.getOrderList();
              } else {
                this.$message({
                  showClose: true,
                  message: response.message,
                  type: "error",
                });

                // 刷新表单
                this.getOrderList();
              }

              this.loading = false;
            });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.loading = false;
          return false;
        }
      });
    },

    // 打开发货对话框
    OpenSendOrderUi(id) {
      // 回显数据
      orderApi.getOrderById(id).then((response) => {
        this.sendProductForm = response.data;
        this.dialogVisibleSendProduct = true;
      });
    },
    // 发货
    sendProduct() {
      this.$refs.sendOrderRef.validate((valid) => {
        if (valid) {
          this.sendProductLoading = true;
          // 提交数据给后台
          orderApi.sendProduct(this.sendProductForm).then((response) => {
            if (response.code === 20000) {
              this.$message({
                showClose: true,
                message: response.message,
                type: "success",
              });
              // 关闭对话框
              this.dialogVisibleSendProduct = false;
              // 刷新表单
              this.getOrderList();
              this.sendProductLoading = false;
            } else {
              this.$message({
                showClose: true,
                message: response.message,
                type: "error",
              });

              // 刷新表单
              this.getOrderList();
              this.sendProductLoading = false;
            }
          });
        } else {
          // 验证不通过
          this.$message({
            showClose: true,
            message: "表单验证不通过",
            type: "error",
          });
          this.sendProductLoading = false;
          return false;
        }
      });
    },
    // 打开批量减库存对话框
    OpenGoodsUi() {
      this.GoodsList = [];
      // 获取指定状态的值
      for (const goods of this.multipleSelection) {
        if (goods.stockStatus === this.seleceStatusCode) {
          this.GoodsList.push(goods);
        }
      }
      this.dialogTableVisibleGoods = true;
    },
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },

    // 更新库存状态
    updateStockStatus() {
      if (
        this.statusCode == null ||
        this.statusCode == undefined ||
        this.statusCode === ""
      )
        return;

      if (
        this.multipleSelectionGoodsList != null ||
        this.multipleSelectionGoodsList != undefined
      ) {
        // 获取IDS
        let ids = this.multipleSelectionGoodsList.map((order) => order.id);
        this.$confirm(
          `您确认要批量更新${ids.length}个订单的状态为${this.statusCode} ?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          orderApi.updateStockStatus(ids, this.statusCode).then((response) => {
            this.$message({
              type: "success",
              message: response.message,
            });
            this.getOrderList();

            // 关闭对话框
            this.dialogTableVisibleGoods = false;
          });
        });
      }
    },
  },
  created() {
    this.getOrderList();
  },
  computed: {
    // 获取商品列表个个型号的数量
    getGoodsListSum() {
      var GoosListSum = {};
      this.multipleSelectionGoodsList.forEach((item) => {
        // 更具+号分割字符串
        var nameList = item.tradeName.split("+");
        nameList.forEach((name) => {
          name = name.trim();
          if (GoosListSum[name] == null || GoosListSum[name] == undefined) {
            GoosListSum[name] = 1;
          } else {
            GoosListSum[name] += 1;
          }
        });
      });

      // this.message 是对 data 中的 message 的引用
      return GoosListSum;
    },
  },
};
</script>

<style scoped>
.el-card {
  margin: 10px;
  font-size: 16px;
}

.el-tag {
  font-size: 16px;
  margin-bottom: 6px;
  margin-right: 4px;
}
</style>
